/*******************************************************************************
 * SDP Project AUT 2012
 * 
 *                ***********Driving Assistant************
 * Team:
 * Gisela, Deidre, Brijesh, Robert
 * 
 * This class is used to integrate Netbeans IDE with Arduino IDE. Main objective
 * is to be able to read the output from the range finder sensor, and output the 
 * reading to be used in the UI.
 * 
 * @version 1.0
 * 
 * Copyright (c) 2011 by DrivingAssistant Team, Inc., All Rights Reserved.
 * 
 ******************************************************************************/
package com.drivingAssistant.gui;

import com.drivingAssistant.model.SoundOff;
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.LineUnavailableException;

public class ArduinoReader implements SerialPortEventListener {
    
    // constants
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 9600;
    
    // variables
    SerialPort serialPort;
    PrintStream out = null;
    SoundOff soundOff = new SoundOff(); // used to output sound later
//    Distance distance = new Distance();
    InputStream input;
    OutputStream output;
    private byte chunk[] = new byte[0];
    private String safeDistance;
    
    /**
     * The port to be used depending on OS.
     */
    private static final String PORT_NAMES[] = {
        "/dev/tty.usbserial-A9007UX1", // Mac OS X
        "/dev/ttyUSB0", // Linux
        "COM3", // Windows
    };

    /**
     * Constructor
     */
    public ArduinoReader() {
        // left empty for now
//        safeDistance = distance.getDistance();
    }

    /**
     * Initialize the Serial port
     */
    private void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        // iterate through, looking for the port
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }

        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (PortInUseException | UnsupportedCommOperationException |
                IOException | TooManyListenersException e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This method will close the port when not being used. Must be called by
     * program.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    @Override
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                int available = input.available();
                chunk = new byte[available];
                input.read(chunk, 0, available);
                // Displayed results are codepage dependent
//                if (safeDistance == Integer.parseInt(new String(chunk))) {
//                    System.out.println("safe distance = " + safeDistance);
//                    try {
//                        soundOff.playClip();
//                    } catch (LineUnavailableException ex) {
//                        Logger.getLogger(ArduinoReader.class.getName())
//                                .log(Level.SEVERE, null, ex);
//                    }
//                }
//                safeDistance = new String(chunk);
                safeDistance = "20";
//                System.out.println("Here in ard val = " + safeDistance);
                System.out.print(new String(chunk));
            } catch (IOException | NumberFormatException e) {
                System.out.println("To slow...");
            }
        }
    }
    
    public String getString() {
        safeDistance = "20";
//        System.out.println("Here in getString() = " + safeDistance);
        return this.safeDistance;
    }

    /**
     * Initialize the arduino and the port receive data
     */
    public void start() {
        initialize();
        
        for (int i=0; i<20; i++) {
            System.out.println("20");
        }
    }

    /**
     * Close down
     */
    public void stop() throws IOException {
        this.close();
        if (serialPort != null) {
            this.serialPort.close();
        }
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        System.out.println("Stoped");
    }
}
